package io.jee.medusa.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.util.MimeType;

import io.jee.medusa.ConstantSupport;
import io.jee.medusa.util.HtmlUtils;

public class CompressorHttpServletResponseWrapper extends HttpServletResponseWrapper {
	
	private StringWriter output = new StringWriter();
	private boolean hasBuff;
	

	public CompressorHttpServletResponseWrapper(HttpServletResponse response) {
		super(response);
	}
	
	@Override
	public PrintWriter getWriter() throws IOException {
		if(hasBuff){
			return new PrintWriter(output);
		}else{
			return super.getWriter();
		}
	}
	
	@Override
	public void setContentType(String type) {
		super.setContentType(type);
		hasBuff = ConstantSupport.PRODUCTION && MimeType.valueOf(type).includes(MimeType.valueOf("text/html"));
	}
	
	public void writerResponse(){
		if(hasBuff){
			String html = output.toString();
			try {
				html = HtmlUtils.crunch(html);
				super.getWriter().write(html);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
